package com.taoding.hfhclient.netty_client;

import com.google.common.collect.Sets;
import com.taoding.hfhclient.netty_client.service.NettyClientMessageImpl;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author liuxinghong
 * @Description: 消息发送失败，定时重发
 * @date 2019/9/6 000616:22
 */
@Component
@Slf4j
public class ReSendTask {

    public static Set<MessageDTO> sendFailedMessage = Sets.newConcurrentHashSet(); //用于存放发送失败的消息

    /**
     * 启用定时任务执行  未发送成功的消息，直到发送成功为止
     */
    @Scheduled(cron = "0/10 * * * * ? ")
    public void resendMessage(){
        HashSet<MessageDTO> removeMessage = Sets.newHashSet();
        NettyClient.future.addListener((ChannelFuture futureListener) -> {
            if (futureListener.isSuccess()) { //监听网络是否已连接
                sendMessage(removeMessage);
            }
        });

    }

    private void sendMessage(HashSet<MessageDTO> removeMessage) {
        if (!sendFailedMessage.isEmpty()){
            for (MessageDTO message: sendFailedMessage){
                ChannelFuture channelFuture = NettyClient.future.channel().writeAndFlush(message);
                channelFuture.addListener((ChannelFuture futureListener) -> {
                    if (futureListener.isSuccess()) { //监听： 发送成功后要干的事
                        removeMessage.add(message);
                        log.info("消息重新发送成功......消息体: "+message.toString());
                    }
                });
            }
            sendFailedMessage.removeAll(removeMessage);
        }
    }
}
